package situ.com.listview;

import android.app.Activity;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.List;

public class DBActivity extends Activity implements View.OnClickListener{
    private TextView mTvId;
    private EditText mEtName;
    private EditText mEtPhone;
    private Button mBtnAdd;
    private Button mBtnQuery;
    private Button mBtnUpdate;
    private Button mBtnDelete;
    private ListView mListView;

    private MyOpenHelper myOpenHelper;

    private MyBaseAdapter myBaseAdapter;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_db);
        mTvId = (TextView) findViewById(R.id.tv_id);
        mEtName = (EditText) findViewById(R.id.et_name);
        mEtPhone = (EditText) findViewById(R.id.et_phone);
        mBtnAdd = (Button) findViewById(R.id.btn_add);
        mBtnQuery = (Button) findViewById(R.id.btn_query);
        mBtnUpdate = (Button) findViewById(R.id.btn_update);
        mBtnDelete = (Button) findViewById(R.id.btn_delete);
        mListView = (ListView) findViewById(R.id.listView);

        mBtnAdd.setOnClickListener(this);
        mBtnQuery.setOnClickListener(this);
        mBtnUpdate.setOnClickListener(this);
        mBtnDelete.setOnClickListener(this);

        // 会创建数据库和里面的表
        myOpenHelper = new MyOpenHelper(getApplicationContext());

        SQLiteDatabase db = myOpenHelper.getReadableDatabase();
        Cursor cursor = db.rawQuery("select _id,name,phone from user", null);
        List<User> list = new ArrayList<>();
        if (cursor != null && cursor.getCount() > 0) {
            while (cursor.moveToNext()) {
                // 每遍历一次拿出数据库里面的一条记录封装成java里面的User对象
                int id = cursor.getInt(0);
                String n = cursor.getString(1);
                String p = cursor.getString(2);
                User user = new User(id, n, p);
                list.add(user);
            }
        }
        db.close();

        myBaseAdapter = new MyBaseAdapter(list);
        mListView.setAdapter(myBaseAdapter);

    }

    @Override
    public void onClick(View v) {
        SQLiteDatabase db;
        switch (v.getId()) {
            case R.id.btn_add:
                db = myOpenHelper.getWritableDatabase();
                String name = mEtName.getText().toString();
                String phone = mEtPhone.getText().toString();
                db.execSQL("insert into user(name,phone) values(?,?)", new Object[]{name, phone});
                db.close();
                Toast.makeText(this, "添加成功", Toast.LENGTH_LONG).show();
                break;
            case R.id.btn_query:
                db = myOpenHelper.getReadableDatabase();
                Cursor cursor = db.rawQuery("select _id,name,phone from user", null);
                List<User> list = new ArrayList<>();
                if (cursor != null && cursor.getCount() > 0) {
                    while (cursor.moveToNext()) {
                        // 每遍历一次拿出数据库里面的一条记录封装成java里面的User对象
                        int id = cursor.getInt(0);
                        String n = cursor.getString(1);
                        String p = cursor.getString(2);
                        User user = new User(id, n, p);
                        list.add(user);
                    }
                }
                db.close();
                for (User user : list) {
                    System.out.println(user);
                }
                // 更新Adapter里面数据
                myBaseAdapter.setList(list);
                // 刷新数据
                myBaseAdapter.notifyDataSetChanged();
                break;
            case R.id.btn_update:
                break;
            case R.id.btn_delete:
                break;
        }
    }

    // 自定义适配器:绑定数据和界面
    // 在IDEA解决一些简单错误:Alt+Enter
    class MyBaseAdapter extends BaseAdapter {
        private List<User> list;

        MyBaseAdapter(List<User> list) {
            this.list = list;
        }

        public void setList(List<User> list) {
            this.list = list;
        }

        // 得到item的总数量
        @Override
        public int getCount() {
            return list.size();
        }

        // 返回指定position位置的条目对象
        @Override
        public Object getItem(int position) {
            return list.get(position);
        }

        // 返回item的id
        @Override
        public long getItemId(int position) {
            return position;
        }

        // 将数据和布局绑定，每绑定一行就调用一次getView
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            // 这个if-else结构是为了缓存，避免每次都去加载
            if (convertView == null) {
                convertView = LayoutInflater.from(getApplicationContext()).inflate(R.layout.list_db_item, parent, false);
                viewHolder = new ViewHolder();
                viewHolder.textView = (TextView) convertView.findViewById(R.id.textView);
                convertView.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertView.getTag();
            }
            viewHolder.textView.setText(list.get(position).toString());

            return convertView;
        }

        // 描述每一个Item布局
        class ViewHolder{
            TextView textView;
        }
    }
}
